package org.jeecg.modules.inOrder1.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import io.swagger.models.auth.In;
import lombok.SneakyThrows;
import org.jeecg.modules.basicCompartment.entity.BasicCompartment;
import org.jeecg.modules.basicCompartment.service.IBasicCompartmentService;
import org.jeecg.modules.basicSkuDetail.entity.BasicSkuDetail;
import org.jeecg.modules.basicSkuDetail.service.IBasicSkuDetailService;
import org.jeecg.modules.inOrder1.entity.Pie;
import org.jeecg.modules.inOrder1.vo.InOrder1Pto;
import org.jeecg.modules.inventoryShelfAdjust.service.IInventoryShelfAdjustService;
import org.jeecg.modules.outOrder1.entity.OutOrder1;
import org.jeecg.modules.outOrder1.entity.OutOrderZi;
import org.jeecg.modules.outOrder1.service.IOutOrder1Service;
import org.jeecg.modules.outOrder1.service.IOutOrderZiService;
import org.jeecg.modules.reportLabel.entity.ReportLabel;
import org.jeecg.modules.reportLabel.service.IReportLabelService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.QRCodeUtil;
import org.jeecg.modules.system.util.ThreadPoolManager;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.inOrder1.entity.InOrderZi;
import org.jeecg.modules.inOrder1.entity.InOrder1;
import org.jeecg.modules.inOrder1.vo.InOrder1Page;
import org.jeecg.modules.inOrder1.service.IInOrder1Service;
import org.jeecg.modules.inOrder1.service.IInOrderZiService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 入库单
 * @Author: jeecg-boot
 * @Date:   2024-01-04
 * @Version: V1.0
 */
@Api(tags="入库单")
@RestController
@RequestMapping("/inOrder1/inOrder1")
@Slf4j
public class InOrder1Controller {
	 @Autowired
	 private IInOrder1Service inOrder1Service;
	 @Autowired
	 private IInOrderZiService inOrderZiService;
	 @Autowired
	 private IReportLabelService reportLabelService;
	 @Autowired
	 private IBasicCompartmentService basicCompartmentService;
	 @Autowired
	 private ThreadPoolManager threadPoolManager;
	 @Autowired
	 private IOutOrder1Service outOrder1Service;
	 @Autowired
	 private IOutOrderZiService outOrderZiService;
	 @Autowired
	 private ISysUserService sysUserService;
	 @Autowired
	 private IInventoryShelfAdjustService inventoryShelfAdjustService;
	 @Autowired
	 private IBasicSkuDetailService skuDetailService;

	 /**
	  * 分页列表查询
	  *
	  * @param inOrder1
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "入库单-分页列表查询")
	 @ApiOperation(value="入库单-分页列表查询", notes="入库单-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<?> queryPageList(InOrder1 inOrder1,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<InOrder1> queryWrapper = QueryGenerator.initQueryWrapper(inOrder1, req.getParameterMap());
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 queryWrapper.likeRight("sys_org_code", user.getOrgCode());
		 Page<InOrder1> page = new Page<InOrder1>(pageNo, pageSize);
		 IPage<InOrder1> pageList = inOrder1Service.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 /**
	  * 入库任务领取--分页列表查询
	  *
	  * @param inOrder1
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "入库单-入库任务领取")
	 @ApiOperation(value="入库单-入库任务领取", notes="入库单-入库任务领取")
	 @GetMapping(value = "/receive")
	 public Result<?> receive(InOrder1 inOrder1,
							  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
							  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
							  HttpServletRequest req) {
		 QueryWrapper<InOrder1> queryWrapper = QueryGenerator.initQueryWrapper(inOrder1, req.getParameterMap());
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 queryWrapper.likeRight("sys_org_code", user.getOrgCode());
		 queryWrapper.eq("is_hang_up", 0);
		 List<String> role = sysUserService.getRole(user.getUsername());
		 if (role.stream().allMatch(s -> s.equals("tally"))) {
			 queryWrapper.eq("in_order_status", 1);
		 } else if (role.stream().allMatch(s -> s.equals("driver"))){
			 queryWrapper.eq("in_order_status", 3);
		 }
		 Page<InOrder1> page = new Page<InOrder1>(pageNo, pageSize);
		 IPage<InOrder1> pageList = inOrder1Service.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @AutoLog(value = "入库单-根据人名、入库单状态查询所有入库单")
	 @ApiOperation(value="入库单-根据人名、入库单状态查询所有入库单",
			 notes="入库单-根据人名、入库单状态查询所有入库单(0:查询全部)")
	 @GetMapping("/getByStatusAndName")
	 public Result<?> getByStatusAndName(@RequestParam(name = "status", defaultValue = "0") Integer status,
										 @RequestParam(name = "tallyClerk",required = false) String tallyClerk,
										 @RequestParam(name = "truckDriver",required = false) String truckDriver){
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 LambdaQueryWrapper<InOrder1> wrapper = Wrappers.lambdaQuery();
		 wrapper.likeRight(InOrder1::getSysOrgCode, user.getOrgCode());
		 List<InOrder1> list;
        if (status != 0) {
            wrapper.eq(InOrder1::getInOrderStatus, status);
        }
		 if (tallyClerk != null && !tallyClerk.trim().isEmpty()) {
			 wrapper.eq(InOrder1::getTallyClerk, tallyClerk);
		 }
		 if (truckDriver != null && !truckDriver.trim().isEmpty()) {
			 wrapper.eq(InOrder1::getTruckDriver, truckDriver);
		 }
		 wrapper.orderByAsc(InOrder1::getInOrderStatus);
		 list = inOrder1Service.list(wrapper);
        return Result.OK(list);
	 }

	 @GetMapping("/operateForApp")
	 public Result<?> operateForApp(InOrder1 inOrder1,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<InOrder1> queryWrapper = QueryGenerator.initQueryWrapper(inOrder1, req.getParameterMap());
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 queryWrapper.likeRight("sys_org_code", user.getOrgCode());
		 List<String> role = sysUserService.getRole(user.getUsername());
		 if (role.stream().allMatch(s -> s.equals("tally"))) {
			 queryWrapper.eq("in_order_status", 2);
			 queryWrapper.eq("tally_clerk", user.getRealname());
		 } else if (role.stream().allMatch(s -> s.equals("driver"))){
			 queryWrapper.eq("in_order_status", 4);
			 queryWrapper.eq("truck_driver", user.getRealname());
		 }
		 Page<InOrder1> page = new Page<InOrder1>(pageNo, pageSize);
		 IPage<InOrder1> pageList = inOrder1Service.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @GetMapping("/recordForApp")
	 public Result<?> recordForApp(InOrder1 inOrder1,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<InOrder1> queryWrapper = QueryGenerator.initQueryWrapper(inOrder1, req.getParameterMap());
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 queryWrapper.likeRight("sys_org_code", user.getOrgCode());
		 List<String> role = sysUserService.getRole(user.getUsername());
		 if (role.stream().allMatch(s -> s.equals("tally"))) {
			 queryWrapper.gt("in_order_status", 2);
			 queryWrapper.eq("tally_clerk", user.getRealname());
		 } else if (role.stream().allMatch(s -> s.equals("driver"))){
			 queryWrapper.gt("in_order_status", 4);
			 queryWrapper.eq("truck_driver", user.getRealname());
		 }
		 Page<InOrder1> page = new Page<InOrder1>(pageNo, pageSize);
		 IPage<InOrder1> pageList = inOrder1Service.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @GetMapping("/getPalletCodeByInOrderId")
	 public Result<?> getPalletCodeByInOrderId(@RequestParam(name = "id") String id){
		 LambdaQueryWrapper<InOrderZi> wrapper = Wrappers.lambdaQuery();
		 wrapper.eq(InOrderZi::getPid, id);
		 wrapper.ne(InOrderZi::getInOrderStatus, 3);
		 wrapper.groupBy(InOrderZi::getPalletCode);
		 List<InOrderZi> list = inOrderZiService.list(wrapper);
		 return Result.OK(list);
	 }

	 /**
	  *   添加
	  *
	  * @param inOrder1Page
	  * @return
	  */
	 @AutoLog(value = "入库单-添加")
	 @ApiOperation(value="入库单-添加", notes="入库单-添加")
	 @PostMapping(value = "/add")
	 public Result<?> add(@RequestBody InOrder1Page inOrder1Page) {
		 Set<String> labels = new HashSet<>();
		 for (InOrderZi inOrderZi : inOrder1Page.getInOrderZiList()){
			 String label = inOrderZi.getPalletCode() + inOrderZi.getSkuCode1();
			 if (labels.contains(label)){
				 return Result.error("入库单中有相同的【识别码+品番】,请先检查入库单,保证【识别码+品番】唯一");
			 } else {
				 labels.add(label);
			 }
			 String sku = inOrderZi.getSkuCode1().replaceAll(" ", "");
			 int index = sku.indexOf("-");
			 String skuSubstring = index != -1 ? sku.substring(0, index + 4) : sku;
			 LambdaQueryWrapper<BasicSkuDetail> wrapper = Wrappers.lambdaQuery();
			 wrapper.likeRight(BasicSkuDetail::getSkuCode, skuSubstring);
			 List<BasicSkuDetail> skus = skuDetailService.list(wrapper);
			 if (skus.isEmpty()){
				 BasicSkuDetail basicSkuDetail = new BasicSkuDetail();
				 basicSkuDetail.setSkuName("不存在的品番");
				 basicSkuDetail.setBackNo(inOrderZi.getSkuCode1());
				 skuDetailService.save(basicSkuDetail);
				 return Result.error("入库单中【"+inOrderZi.getSkuCode1()+"】品番不存在,若确认无误，请先维护品番数据");
			 }
			 if(skus.size() > 1){
				 BasicSkuDetail basicSkuDetail = new BasicSkuDetail();
				 basicSkuDetail.setBackNo(inOrderZi.getSkuCode1());
				 skuDetailService.save(basicSkuDetail);
				 return Result.error("入库单中【"+inOrderZi.getSkuCode1()+"】品番,匹配到多条数据,请先检查品番表数据是否重复");
			 }
		 }
		 InOrder1 inOrder1 = new InOrder1();
		 BeanUtils.copyProperties(inOrder1Page, inOrder1);
		 inOrder1Service.saveMain(inOrder1, inOrder1Page.getInOrderZiList());
		 return Result.OK("添加成功！");
	 }

	 /**
	  *  编辑
	  *
	  * @param inOrder1Page
	  * @return
	  */
	 @AutoLog(value = "入库单-编辑")
	 @ApiOperation(value="入库单-编辑", notes="入库单-编辑")
	 @PutMapping(value = "/edit")
	 public Result<?> edit(@RequestBody InOrder1Page inOrder1Page) {
		 InOrder1 inOrder1 = new InOrder1();
		 BeanUtils.copyProperties(inOrder1Page, inOrder1);
		 InOrder1 inOrder1Entity = inOrder1Service.getById(inOrder1.getId());
		 if(inOrder1Entity==null) {
			 return Result.error("未找到对应数据");
		 }
		 if (inOrder1Entity.getInOrderStatus()==5 || inOrder1Entity.getInOrderStatus()==12 || inOrder1Entity.getInOrderStatus()==13){
			 return Result.error("入库单已完结，禁止编辑！");
		 }
		 inOrder1Service.updateMain(inOrder1, inOrder1Page.getInOrderZiList());
		 return Result.OK("编辑成功!");
	 }

	 /**
	  *   通过id删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "入库单-通过id删除")
	 @ApiOperation(value="入库单-通过id删除", notes="入库单-通过id删除")
	 @DeleteMapping(value = "/delete")
	 public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		 inOrder1Service.delMain(id);
		 return Result.OK("删除成功!");
	 }

	 /**
	  *  批量删除
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "入库单-批量删除")
	 @ApiOperation(value="入库单-批量删除", notes="入库单-批量删除")
	 @DeleteMapping(value = "/deleteBatch")
	 public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		 this.inOrder1Service.delBatchMain(Arrays.asList(ids.split(",")));
		 return Result.OK("批量删除成功！");
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "入库单-通过id查询")
	 @ApiOperation(value="入库单-通过id查询", notes="入库单-通过id查询")
	 @GetMapping(value = "/queryById")
	 public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		 InOrder1 inOrder1 = inOrder1Service.getById(id);
		 if(inOrder1==null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(inOrder1);
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "入库单子表通过主表ID查询")
	 @ApiOperation(value="入库单子表主表ID查询", notes="入库单子表-通主表ID查询")
	 @GetMapping(value = "/queryInOrderZiByMainId")
	 public Result<?> queryInOrderZiListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<InOrderZi> inOrderZiList = inOrderZiService.selectByMainId(id);
		 return Result.OK(inOrderZiList);
	 }

	 @AutoLog(value = "入库单子表通过整托主表ID和标识码查询")
	 @ApiOperation(value="入库单子表通过整托主表ID和标识码查询", notes="入库单子表-通过整托主表ID和标识码查询")
	 @GetMapping(value = "/queryInOrderZiByMainIdAndPalletCode")
	 public Result<?> queryInOrderZiByMainIdAndPalletCode(@RequestParam(name="id") String id, @RequestParam(name="palletCode") String palletCode) {
		 LambdaQueryWrapper<InOrderZi> wrapper = Wrappers.lambdaQuery();
		 wrapper.eq(InOrderZi::getPid, id);
		 wrapper.eq(InOrderZi::getPalletCode, palletCode);
		 List<InOrderZi> list = inOrderZiService.list(wrapper);
		 return Result.OK(list);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param inOrder1
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InOrder1 inOrder1) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<InOrder1> queryWrapper = QueryGenerator.initQueryWrapper(inOrder1, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<InOrder1> queryList = inOrder1Service.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<InOrder1> inOrder1List = new ArrayList<InOrder1>();
      if(oConvertUtils.isEmpty(selections)) {
          inOrder1List = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          inOrder1List = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<InOrder1Page> pageList = new ArrayList<InOrder1Page>();
      for (InOrder1 main : inOrder1List) {
          InOrder1Page vo = new InOrder1Page();
          BeanUtils.copyProperties(main, vo);
          List<InOrderZi> inOrderZiList = inOrderZiService.selectByMainId(main.getId());
          vo.setInOrderZiList(inOrderZiList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "入库单列表");
      mv.addObject(NormalExcelConstants.CLASS, InOrder1Page.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("入库单数据", "导出人:"+sysUser.getRealname(), "入库单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<InOrder1Page> list = ExcelImportUtil.importExcel(file.getInputStream(), InOrder1Page.class, params);
			  Set<String> labels = new HashSet<>();
              for (InOrder1Page page : list) {
				  for (InOrderZi inOrderZi : page.getInOrderZiList()){
					  String label = inOrderZi.getPalletCode() + inOrderZi.getSkuCode1();
					  if (labels.contains(label)){
						  return Result.error("入库单中有相同的【识别码+品番】,请先检查入库单,保证【识别码+品番】唯一");
					  } else {
						  labels.add(label);
					  }
					  String sku = inOrderZi.getSkuCode1().replaceAll(" ", "");
					  int index = sku.indexOf("-");
					  String skuSubstring = index != -1 ? sku.substring(0, index + 4) : sku;
					  LambdaQueryWrapper<BasicSkuDetail> wrapper = Wrappers.lambdaQuery();
					  wrapper.likeRight(BasicSkuDetail::getSkuCode, skuSubstring);
					  List<BasicSkuDetail> skus = skuDetailService.list(wrapper);
					  if (skus.isEmpty()){
						  BasicSkuDetail basicSkuDetail = new BasicSkuDetail();
						  basicSkuDetail.setSkuName("不存在的品番");
						  basicSkuDetail.setBackNo(inOrderZi.getSkuCode1());
						  skuDetailService.save(basicSkuDetail);
						  return Result.error("入库单中【"+inOrderZi.getSkuCode1()+"】品番不存在,若确认无误，请先维护品番数据");
					  }
					  if(skus.size() > 1){
						  BasicSkuDetail basicSkuDetail = new BasicSkuDetail();
						  basicSkuDetail.setBackNo(inOrderZi.getSkuCode1());
						  skuDetailService.save(basicSkuDetail);
						  return Result.error("入库单中【"+inOrderZi.getSkuCode1()+"】品番,匹配到多条数据,请先检查品番表数据是否重复");
					  }
				  }
                  InOrder1 po = new InOrder1();
                  BeanUtils.copyProperties(page, po);
                  inOrder1Service.saveMain(po, page.getInOrderZiList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 /**
	  * 任务分配
	  */
	 @AutoLog(value = "任务分配")
	 @ApiOperation(value="任务分配", notes="任务分配")
	 @PostMapping(value = "/taskAllocation")
	 public Result<?> taskAllocation(@RequestBody InOrder1 inOrder) {
		 if (inOrder.getIsHangUp().equals(1)){
			 return Result.error("该单据已挂单禁止操作！");
		 }
		 //	更新数据库数据
		 inOrder1Service.updateById(inOrder);
		 return Result.OK("分配成功！");
	 }

	 @AutoLog(value = "理货员领取入库单")
	 @ApiOperation(value="理货员领取入库单", notes="理货员领取入库单")
	 @PostMapping("/tallyReceiveOrder")
	 public Result<?> tallyReceiveOrder(@RequestBody InOrder1 inOrder, @RequestParam(name = "username") String username){
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 List<String> role = sysUserService.getRole(user.getUsername());
		 if (role.stream().noneMatch(s -> s.equals("tally"))) {
			 return Result.error("当前登录用户不是理货员,请先联系理货员进行收货操作！");
		 }
		 return getReceiveResult(username, 2, inOrder);
	 }

	 @AutoLog(value = "理货扫描二维码")
	 @ApiOperation(value="理货扫描二维码", notes="理货扫描二维码")
	 @PostMapping("/checkCode")
	 public Result<?> checkCode(@RequestBody InOrder1 inOrder, @RequestParam(name = "code") String code){
		 Integer isHangUp = inOrder.getIsHangUp();
		 if (1 == isHangUp){
			 return Result.error("此单已挂单,请联系管理员解挂后再进行操作！");
		 }
		 int i = reportLabelService.countByCode(code);
		 if (i > 0){
			 return Result.error("该二维码已存在,请重新扫码！");
		 }
		 List<InOrderZi> inOrderZis = inOrderZiService.selectByMainId(inOrder.getId());
		 for (InOrderZi inOrderZi : inOrderZis) {
			 String skuCode1 = inOrderZi.getSkuCode1();
			 if (code.contains(skuCode1)) {
				 int workNum = inOrderZi.getWorkNum();
				 if (workNum >= inOrderZi.getTrayNum()){
					 return Result.error("当前品番已作业完成,请核对！");
				 }
				 inOrderZi.setWorkNum(workNum+1);
				 if (workNum+1 == inOrderZi.getTrayNum() && inOrderZi.getStaging() == 0){
					 inOrderZi.setInOrderStatus(3);
				 }
				 inOrderZiService.updateById(inOrderZi);
                 Runnable task = () -> {
					 try {
						 ReportLabel reportLabel = getReportLabel(inOrderZi, inOrder, workNum);
						 reportLabel.setBarCode(code);
						 reportLabelService.save(reportLabel);
					 } catch (Exception e) {
						 log.error("线程池调用createLabels方法出现异常", e);
					 }
				 };
				 threadPoolManager.executeTask(task);
				 return getResult(inOrder);
			 }
		 }
		 return Result.error("该入库单无此品番信息,请核对！");
	 }

	 @AutoLog(value = "DICH-理货扫描二维码")
	 @ApiOperation(value="DICH-理货扫描二维码", notes="DICH-理货扫描二维码")
	 @PostMapping("/DICHCheckCode")
	 public Result<?> DICHCheckCode(@RequestBody InOrder1 inOrder, @RequestParam(name = "code") String code,
									@RequestParam(name = "palletCode") String palletCode){
		 Integer isHangUp = inOrder.getIsHangUp();
		 if (1 == isHangUp){
			 return Result.error("此单已挂单,请联系管理员解挂后再进行操作！");
		 }
		 List<InOrderZi> inOrderZis1 = inOrderZiService.selectByMainId(inOrder.getId());
		 if (inOrderZis1.stream().allMatch(inOrderZi -> 3==inOrderZi.getInOrderStatus())){
			 return Result.error("当前入库单已作业完成,请联系叉车司机进行上架操作！");
		 }
		 int i = reportLabelService.countByCode(code);
		 if (i > 0){
			 return Result.error("该二维码已存在,请重新扫码！");
		 }
		 List<InOrderZi> inOrderZis = inOrderZiService.selectByMainIdAndPalletCode(inOrder.getId(), palletCode);
		 if (inOrderZis.stream().allMatch(inOrderZi -> 3==inOrderZi.getInOrderStatus())){
			 return Result.error("当前托盘识别码已作业完成,请检查或更换！");
		 }
		 for (InOrderZi inOrderZi : inOrderZis){
			 inOrderZi.setInOrderStatus(3);
		 }
		 inOrderZiService.updateBatchById(inOrderZis);

		 Runnable task = () -> {
			 try {
				 List<ReportLabel> reportLabels = getReportLabel(inOrderZis, inOrder, code);
				 reportLabelService.saveBatch(reportLabels);
			 } catch (Exception e) {
				 log.error("线程池调用createLabels方法出现异常", e);
			 }
		 };
		 threadPoolManager.executeTask(task);
		 return getResult(inOrder);
	 }

	 @AutoLog(value = "叉车司机领取入库单")
	 @ApiOperation(value="叉车司机领取入库单", notes="叉车司机领取入库单")
	 @PostMapping("/driverReceiveOrder")
	 public Result<?> driverReceiveOrder(@RequestBody InOrder1 inOrder, @RequestParam(name = "username") String username){
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 List<String> role = sysUserService.getRole(user.getUsername());
		 if (role.stream().noneMatch(s -> s.equals("driver"))) {
			 return Result.error("当前登录用户不是叉车司机,请先联系叉车司机进行上架操作！");
		 }
		 return getReceiveResult(username, 4, inOrder);
	 }

	 @AutoLog(value = "叉车司机扫描二维码上架")
	 @ApiOperation(value="叉车司机扫描二维码上架", notes="叉车司机扫描二维码上架")
	 @PostMapping("/shelving")
	 public Result<?> shelving(@RequestBody InOrder1 inOrder, @RequestParam(name = "compartmentCode") String compartmentCode, @RequestParam(name = "code") String code){
		 Integer isHangUp = inOrder.getIsHangUp();
		 if (1 == isHangUp){
			 return Result.error("此单已挂单,请联系管理员解挂后再进行操作！");
		 }
		 BasicCompartment basicCompartment = basicCompartmentService.getByCompartmentCode(compartmentCode);
		 if (basicCompartment == null || basicCompartment.getShelfCode() == null){
			 return Result.error("非法信息！货位码或货架码不存在！");
		 }
		 LambdaQueryWrapper<ReportLabel> wrapper = Wrappers.lambdaQuery();
		 wrapper.eq(ReportLabel::getBarCode, code);
		 List<ReportLabel> labels = reportLabelService.list(wrapper);
		 if (labels.isEmpty() || labels.stream().anyMatch(label -> !label.getInOrderId().equals(inOrder.getId()))) {
			 return Result.error("此二维码不属于当前入库单！请重新扫码！");
		 }
		 String shelfCode = basicCompartment.getShelfCode();
		 Map<String, List<String>> map = new HashMap<>();
		 for (ReportLabel label : labels){
			 String inOrderZiId = label.getInOrderZiId();
			 String split = label.getLabelNumber().split("_")[1];
			 String sku = label.getSkuCode1() + " / " + label.getBoxNum() + " 件";
			 InOrderZi inOrderZi = inOrderZiService.getById(inOrderZiId);
			 if (inOrderZi.getStaging() == 1){
				 return Result.error("此货物为出库暂存区货物！无需操作！");
			 }
			 int shelfNum = inOrderZi.getShelfNum();
			 if (shelfNum >= inOrderZi.getTrayNum()){
				 return Result.error("当前品番已作业完成,请核对！");
			 }
			 inOrderZi.setShelfNum(shelfNum+1);
			 if (shelfNum+1 == inOrderZi.getTrayNum()){
				 inOrderZi.setInOrderStatus(5);
			 }
			 label.setShelfCode(shelfCode);
			 label.setCompartmentCode(compartmentCode);
			 label.setStatus(5);
			 label.setStackingDate(new Date());
			 if (map.containsKey(split)){
				 map.get(split).add(sku);
			 } else {
				 List<String> labelList = new LinkedList<>();
				 labelList.add(sku);
				 map.put(split, labelList);
			 }
			 inOrderZiService.updateById(inOrderZi);
		 }
		 reportLabelService.updateBatchById(labels);
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 LambdaQueryWrapper<InOrderZi> wrapper1 = Wrappers.lambdaQuery();
		 wrapper1.in(InOrderZi::getInOrderStatus, 3, 4);
		 wrapper1.eq(InOrderZi::getPid, inOrder.getId());
		 wrapper1.likeRight(InOrderZi::getSysOrgCode, user.getOrgCode());
		 List<InOrderZi> list = inOrderZiService.list(wrapper1);
		 Map<String, Object> map1 = new HashMap<>();
		 for (String key : map.keySet()){
			 map1.put("pallet", key);
			 map1.put("sku", map.get(key));
		 }
		 if (list.isEmpty()) {
			 inOrder.setTruckTime(new Date());
			 inOrder.setInOrderStatus(5);
			 inOrder1Service.updateById(inOrder);
			 return Result.OK("操作成功！当前入库单已无新任务", map1);
		 } else {
			 return Result.OK("操作成功！", map1);
		 }
	 }

	 @NotNull
	 private Result<?> getReceiveResult(String username, int val, InOrder1 inOrder) {
		 Integer isHangUp = inOrder.getIsHangUp();
		 if (1 == isHangUp){
			 return Result.error("此单已挂单,请联系管理员解挂后领取！");
		 }
		 int inOrderStatus = inOrder.getInOrderStatus();
		 if (inOrderStatus != val-1){
			 return Result.error("当前单据状态不符合要求,无法领取！");
		 }
		 LambdaQueryWrapper<InOrder1> wrapper = Wrappers.lambdaQuery();
		 if (val == 2){
			 wrapper.eq(InOrder1::getTallyClerk, username);
		 }else {
			 wrapper.eq(InOrder1::getTruckDriver, username);
		 }
		 wrapper.eq(InOrder1::getInOrderStatus, val);
		 wrapper.eq(InOrder1::getIsHangUp, 0);
		 List<InOrder1> list = inOrder1Service.list(wrapper);
		 if (list.isEmpty()) {
			 inOrder.setInOrderStatus(val);
			 if (2 == val){
				 inOrder.setTallyClerk(username);
				 inOrder.setTallyTaskTime(new Date());
			 } else if (4 == val){
				 inOrder.setTruckDriver(username);
				 inOrder.setTruckTaskTime(new Date());
			 }
			 List<InOrderZi> inOrderZis = inOrderZiService.selectByMainId(inOrder.getId());
			 for (InOrderZi inOrderZi : inOrderZis) {
				 if (inOrderZi.getStaging() == 2){
					 inOrderZi.setInOrderStatus(val);
				 }
			 }
			 inOrder1Service.updateMain(inOrder, inOrderZis);
			 return Result.OK("领取成功!");
		 }
		 return Result.error("你当前有未完成的入库单,请先作业！");
	 }

	 @NotNull
	 private static ReportLabel getReportLabel(InOrderZi inOrderZi, InOrder1 inOrder1, int i) {
		 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		 String dateStr = LocalDate.now().format(formatter);
		 String labelNumber = dateStr + "_" + inOrderZi.getPid() + "_" + inOrderZi.getSkuCode1() + "_" + String.format("%05d", i + 1);
		 ReportLabel reportLabel = new ReportLabel();
		 reportLabel.setSysOrgCode(inOrder1.getSysOrgCode())
				 .setCustomerCode(inOrder1.getCustomerCode())//客户编码
				 .setSkuCode1(inOrderZi.getSkuCode1())//品番编码1
				 .setSkuCode2(inOrderZi.getSkuCode2())//品番编码1
				 .setBoxNum(inOrderZi.getBoxNum())//箱数
				 .setPcs(inOrderZi.getPcs())//规格
				 .setPcsNum(inOrderZi.getPcsNum())//件数
				 .setLabelNumber(labelNumber)//标签号
				 .setInOrderId(inOrderZi.getPid())//入库单id
				 .setInOrderZiId(inOrderZi.getId())//入库单子表id
				 .setInvoiceNum(inOrder1.getInvoiceNum())//发票号
				 .setBatchNumber(inOrder1.getBatchNumber())//批次号
				 .setIsFreeze(0)//未冻结
				 .setLockStatus(1)//未锁定
				 .setInDate(new Date())//入库日期
				 .setSourceOfGoods(inOrder1.getSourceOfGoods())//到货方式
				 .setInOrderType(inOrder1.getInOrderType())//入库类型
				 .setPackagingType(inOrderZi.getPackagingType())//包装类型
				 .setProductionDate(inOrderZi.getProductionDate())//生产日期
				 .setSkuType(inOrder1.getSkuType())//货品种类
				 .setFoaming(0);//未发泡
		 if (inOrderZi.getStaging() == 1){
			 reportLabel.setStatus(8);
			 reportLabel.setShelfCode("备货暂存区");
			 reportLabel.setCompartmentCode("备货暂存区");
		 } else {
			 reportLabel.setStatus(3);//1:待收货, 2:收货中, 3:已收货, 4:上架中, 5:已上架, 6:待备货, 7:备货中, 8:已备货 9:出库中, 10:已出库
		 }
		 return reportLabel;
	 }

	 @NotNull
	 private static List<ReportLabel> getReportLabel(List<InOrderZi> inOrderZis, InOrder1 inOrder1, String code) {
		 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		 String dateStr = LocalDate.now().format(formatter);
		 List<ReportLabel> reportLabels = new ArrayList<>();
		 for (InOrderZi inOrderZi : inOrderZis){
			 String labelNumber = dateStr + "_" + inOrderZi.getPalletCode() + "_" + inOrderZi.getSkuCode1() + "_" + inOrder1.getId();
			 ReportLabel reportLabel = new ReportLabel();
			 reportLabel.setSysOrgCode(inOrder1.getSysOrgCode())
					 .setCustomerCode(inOrder1.getCustomerCode())//客户编码
					 .setSkuCode1(inOrderZi.getSkuCode1())//品番编码1
					 .setSkuCode2(inOrderZi.getSkuCode2())//品番编码2
					 .setBoxNum(inOrderZi.getBoxNum())//箱数
					 .setPcs(inOrderZi.getPcs())//规格
					 .setPcsNum(inOrderZi.getPcsNum())//件数
					 .setLabelNumber(labelNumber)//标签号
					 .setInOrderId(inOrderZi.getPid())//入库单id
					 .setInOrderZiId(inOrderZi.getId())//入库单子表id
					 .setInvoiceNum(inOrder1.getInvoiceNum())//发票号
					 .setBatchNumber(inOrder1.getBatchNumber())//批次号
					 .setIsFreeze(0)//未冻结
					 .setLockStatus(1)//未锁定
					 .setInDate(new Date())//入库日期
					 .setActivated(inOrderZi.getBoxNum())//可用库存
					 .setSourceOfGoods(inOrder1.getSourceOfGoods())//到货方式
					 .setInOrderType(inOrder1.getInOrderType())//入库类型
					 .setPackagingType(inOrderZi.getPackagingType())//包装类型
					 .setProductionDate(inOrderZi.getProductionDate())//生产日期
					 .setSkuType(inOrder1.getSkuType())//货品种类
					 .setFoaming(0)//未发泡
					 .setBarCode(code)
					 .setStatus(3);//1:待收货, 2:收货中, 3:已收货, 4:上架中, 5:已上架, 6:待备货, 7:备货中, 8:已备货 9:出库中, 10:已出库
			 reportLabels.add(reportLabel);
		 }
		 return reportLabels;
	 }

	 @NotNull
	 private Result<?> getResult(InOrder1 inOrder1) {
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 LambdaQueryWrapper<InOrderZi> wrapper = Wrappers.lambdaQuery();
//		 wrapper.eq(InOrderZi::getInOrderStatus, 2);
		 wrapper.eq(InOrderZi::getPid, inOrder1.getId());
		 wrapper.likeRight(InOrderZi::getSysOrgCode, user.getOrgCode());
		 List<InOrderZi> list = inOrderZiService.list(wrapper);
		 boolean anyMatch = list.stream().anyMatch(inOrderZiItem -> inOrderZiItem.getInOrderStatus() == 1);
		 boolean allMatch = list.stream().allMatch(inOrderZiItem -> inOrderZiItem.getStaging() == 1);
		 if (anyMatch){
			 return Result.OK("操作成功！", list);
		 } else {
			 inOrder1.setTallyClerkTime(new Date());
			 if (allMatch){
				 inOrder1.setInOrderStatus(12);
			 } else if (inOrder1.getTruckDriver() == null || inOrder1.getTruckDriver().isEmpty()){
				 inOrder1.setInOrderStatus(3);
			 } else {
				 inOrder1.setInOrderStatus(4);
			 }
			 inOrder1Service.updateById(inOrder1);
			 return Result.OK("操作成功！当前入库单已无新任务", null);
		 }
	 }


	 @AutoLog(value = "理货选择入库单子表一条数据通过")
	 @ApiOperation(value="理货选择入库单子表一条数据通过", notes="理货选择入库单子表一条数据通过")
	 @PostMapping("/checkPass")
	 public Result<?> checkPass(@RequestBody InOrderZi inOrderZi){
		 inOrderZi.setInOrderStatus(3);
		 inOrderZiService.updateById(inOrderZi);
		 InOrder1 inOrder1 = inOrder1Service.getById(inOrderZi.getPid());
		 Runnable task = () -> {
			 try {
				 int trayNum = inOrderZi.getTrayNum();
				 List<ReportLabel> labels = new ArrayList<>();
				 for (int i = 0; i < trayNum; i++) {
					 ReportLabel reportLabel = getReportLabel(inOrderZi, inOrder1, i);
					 labels.add(reportLabel);
				 }
				 reportLabelService.saveBatch(labels);
			 } catch (Exception e) {
				 log.error("线程池调用createLabels方法出现异常", e);
			 }
		 };
		 threadPoolManager.executeTask(task);
		 return getResult(inOrder1);
	 }

	 /**
	  * 理货员--一键待入库转待出库
	  * @param inOrder1Pto
	  * @return
	  */
	 @AutoLog(value = "理货员--一键待入库转待出库")
	 @ApiOperation(value="理货员--一键待入库转待出库", notes="理货员--一键待入库转待出库")
	 @PostMapping("/tallyClerkOperation")
	 public Result<?> tallyClerkOperation(@RequestBody InOrder1Pto inOrder1Pto){
		 InOrder1 inOrder1 = inOrder1Pto.getInOrder1();
		 OutOrder1 outOrder1 = inOrder1Pto.getOutOrder1();

		 // 判断单据状态和客户是否符合要求
		 if (inOrder1.getInOrderStatus() != 3 || outOrder1.getOutOrderStatus() != 6 && outOrder1.getOutOrderStatus() != 11){
			 return Result.error("单据状态不符合要求，请确认后再提交！");
		 }
		 if (!Objects.equals(inOrder1.getCustomerCode(), outOrder1.getCustomerCode())){
			 return Result.error("单据客户不符合要求，请确认后再提交！");
		 }

		 // 判断发票号是否符合要求
		 if (outOrder1.getOutOrderRules().equals(3)  && !Objects.equals(inOrder1.getInvoiceNum(), outOrder1.getInvoicenum())){
			 return Result.error("单据发票号不符合要求，请确认后再提交！");
		 }

		 // 判断货品属性是否符合要求
		 List<InOrderZi> inOrderZiList = inOrderZiService.selectByMainId(inOrder1.getId());
		 List<OutOrderZi> outOrderZiList = outOrderZiService.selectByMainId(outOrder1.getId());
		 if (inOrderZiList.size() != outOrderZiList.size()){
			 return Result.error("单据货品品番数量不符合要求，请确认后再提交！");
		 }
		 // 判断生产日期是否符合要求
		 boolean result = true;
		 if (outOrder1.getOutOrderRules().equals(2)) {
			 result = inOrderZiList.stream().allMatch(inOrderZi -> outOrderZiList.stream()
					 .anyMatch(outOrderZi -> compareElements1(inOrderZi, outOrderZi)));
		 }else {
			 result = inOrderZiList.stream().allMatch(inOrderZi -> outOrderZiList.stream()
					 .anyMatch(outOrderZi -> compareElements(inOrderZi, outOrderZi)));
		 }

		 if (!result){
			 return Result.error("单据货品属性不符合要求，请确认后再提交！");
		 }

		 // 更新单据状态
		 inOrder1.setInOrderStatus(12); // 转待出库
		 inOrder1Service.updateById(inOrder1);
		 outOrder1.setOutOrderStatus(8); // 已备货
		 outOrder1Service.updateById(outOrder1);
		 outOrderZiList.forEach(item -> item.setOutOrderStatus(8));
		 outOrderZiService.updateBatchById(outOrderZiList);

		 // 更新标签状态和关联出库单
		 LambdaQueryWrapper<ReportLabel> reportLabelLqw = Wrappers.lambdaQuery(ReportLabel.class);
		 reportLabelLqw.eq(ReportLabel::getInOrderId, inOrder1.getId());
		 List<ReportLabel> reportLabels = reportLabelService.list(reportLabelLqw);
		 reportLabels.forEach(item -> {
			 item.setStatus(8);
			 item.setOutOrderId(outOrder1.getId());
		 });
		 reportLabelService.updateBatchById(reportLabels);

		 return Result.OK("转待出库成功！");
	 }

	 /**
	  *  比对入库单子表与出库单子表属性
	  * @param inOrderZi
	  * @param outOrderZi
	  * @return
	  */
	 private static boolean compareElements(InOrderZi inOrderZi, OutOrderZi outOrderZi) {
		 return (Objects.equals(outOrderZi.getSkuCode(), inOrderZi.getSkuCode1()) ||
				 Objects.equals(outOrderZi.getSkuCode(), inOrderZi.getSkuCode2())) &&
//				 outOrderZi.getProductionDate().compareTo(inOrderZi.getProductionDate())==0 &&
                 Objects.equals(outOrderZi.getTrayNum(), inOrderZi.getTrayNum()) &&
                 Objects.equals(outOrderZi.getBoxNum(), inOrderZi.getBoxNum()) &&
                 Objects.equals(outOrderZi.getPcs(), inOrderZi.getPcs()) &&
                 Objects.equals(outOrderZi.getPcsNum(), inOrderZi.getPcsNum()) &&
                 Objects.equals(outOrderZi.getPackagingType(), inOrderZi.getPackagingType());
	 }
	 private static boolean compareElements1(InOrderZi inOrderZi, OutOrderZi outOrderZi) {
		 return (Objects.equals(outOrderZi.getSkuCode(), inOrderZi.getSkuCode1()) ||
				 Objects.equals(outOrderZi.getSkuCode(), inOrderZi.getSkuCode2())) &&
//				 outOrderZi.getProductionDate().compareTo(inOrderZi.getProductionDate())==0 &&
				 Objects.equals(outOrderZi.getTrayNum(), inOrderZi.getTrayNum()) &&
				 Objects.equals(outOrderZi.getBoxNum(), inOrderZi.getBoxNum()) &&
				 Objects.equals(outOrderZi.getPcs(), inOrderZi.getPcs()) &&
				 Objects.equals(outOrderZi.getPcsNum(), inOrderZi.getPcsNum()) &&
				 Objects.equals(outOrderZi.getPackagingType(), inOrderZi.getPackagingType());
	 }

	 /**
	  * 首页--饼状图数据展示
	  */
	 @AutoLog(value = "首页--饼状图数据展示")
	 @ApiOperation(value="首页--饼状图数据展示", notes="首页--饼状图数据展示")
	 @GetMapping(value = "/getPie")
	 public Result<?> getPie() {
		 Integer inCount = inOrder1Service.getInOrderCount();// 今日入库总数
		 Integer outCount = outOrder1Service.getOutOrderCount();// 今日出库总数
		 Integer shelfAdjusCount = inventoryShelfAdjustService.getShelfAdjusCount();// 今日理货总数
		 Pie pie1 = new Pie("今日入库", inCount);
		 Pie pie2 = new Pie("今日出库", outCount);
		 Pie pie3 = new Pie("今日理货", shelfAdjusCount);
		 List<Pie> pies = new ArrayList<>();
		 pies.add(pie1);
		 pies.add(pie2);
		 pies.add(pie3);
		 return Result.OK(pies);
	 }

//	 @PostMapping("/changeOut")
//	 public Result<?> changeOut(@RequestParam(name="virtually") String virtually,@RequestParam(name="ids") List<String> ids){
//		 List<InOrderZi> inOrderZis = inOrderZiService.listByIds(ids);
//		 LambdaQueryWrapper<ReportLabel> wrapper = Wrappers.lambdaQuery();
//		 wrapper.in(ReportLabel::getInOrderZiId, ids);
//		 List<ReportLabel> labels = reportLabelService.list(wrapper);
//		 for (InOrderZi inOrderZi : inOrderZis){
//			 inOrderZi.setInOrderStatus(12);
//		 }
//		 for (ReportLabel reportLabel : labels){
//			 reportLabel.
//		 }
//		 inOrderZiService.updateBatchById(inOrderZis);
//	 }

	 //生成二维码并将其返回给前端调用者
	 @SneakyThrows
	 @GetMapping("/getQRCodes")
	 public void generateV2s(@RequestParam(name = "id", required = true) String id, HttpServletResponse response) {
		 // 生成二维码图片
		 response.setContentType("application/octet-stream");
		 response.setHeader("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".zip");// 压缩包名
		 ZipOutputStream zos = null;
		 try {
			 zos = new ZipOutputStream(response.getOutputStream());
			 // zos.setLevel(5);//压缩等级
			 InOrder1 inOrder1 = inOrder1Service.getById(id);
			 List<InOrderZi> inOrderZis = inOrderZiService.selectByMainId(id);
			 Calendar calendar = Calendar.getInstance();
			 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 String format = formatter.format(calendar.getTime());
			 Map<String, JSONObject> map = new HashMap<>();
			 for (InOrderZi inOrderZi : inOrderZis){
				 if (!map.containsKey(inOrderZi.getPalletCode())){
					 JSONObject jsonObject = new JSONObject();
					 if (inOrder1.getInvoiceNum() != null && !inOrder1.getInvoiceNum().isEmpty()) jsonObject.put("批次号", inOrder1.getInvoiceNum());
					 jsonObject.put("整托标识码", inOrderZi.getPalletCode());
					 jsonObject.put("品番", inOrderZi.getSkuCode1());
					 if (inOrder1.getCustomerCode() != null && !inOrder1.getCustomerCode().isEmpty()) jsonObject.put("客户", inOrder1.getCustomerCode());
					 jsonObject.put("日期", format);
					 map.put(inOrderZi.getPalletCode(), jsonObject);
				 } else {
					 JSONObject jsonObject = map.get(inOrderZi.getPalletCode());
					 String s = (String) jsonObject.get("品番");
					 jsonObject.put("品番", s + " / " + inOrderZi.getSkuCode1());
				 }
			 }
			 for (String key : map.keySet()){
				 long l = System.currentTimeMillis();
				 StringBuilder dataStr = new StringBuilder();
				 dataStr.append(key).append("_")
						 .append(inOrder1.getCustomerCode()).append("_")
						 .append(inOrder1.getInvoiceNum()).append("_")
						 .append(l);
				 JSONObject jsonObject = map.get(key);
				 BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(dataStr.toString(), false, jsonObject);
				 InputStream inputStream = bufferedImageToInputStream(bufferedImage);// 将bufferedImage转成inputStream
				 zos.putNextEntry(new ZipEntry(l + ".png")); // 压缩文件名称 设置ZipEntry对象
				 int temp = 0;
				 while ((temp = inputStream.read()) != -1) { // 读取内容
					 zos.write(temp); // 压缩输出
				 }
				 inputStream.close(); // 关闭输入流
			 }
		 } catch (Exception e) {
		 } finally {
			 try {
				 if (null != zos) {
					 zos.flush();
					 zos.close();
				 }
			 } catch (IOException e) {
			 }
		 }
	 }

	 /**
	  * 将BufferedImage转换为InputStream
	  *
	  * @param image
	  * @return
	  */
	 public InputStream bufferedImageToInputStream(BufferedImage image) {
		 ByteArrayOutputStream os = new ByteArrayOutputStream();
		 try {
			 ImageIO.write(image, "png", os);
			 return new ByteArrayInputStream(os.toByteArray());
		 } catch (IOException e) {
			 log.error("bufferedImageToInputStream方法出现异常：", e);
		 }
		 return null;
	 }

 }
